package com.vshop.controller.other;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.vshop.entity.comentity.Country;
import com.vshop.entity.interfacerequest.ExceptionRequest;
import com.vshop.entity.interfacerequest.countrylist.request.RequestCountryList;
import com.vshop.entity.interfacerequest.countrylist.request.RequestCountryListData;
import com.vshop.entity.interfacerequest.countrylist.request.RequestCountryListTradeData;
import com.vshop.entity.interfacerequest.countrylist.response.ResponseCountryList;
import com.vshop.entity.interfacerequest.countrylist.response.ResponseCountryListData;
import com.vshop.entity.interfacerequest.countrylist.response.ResponseCountryListTradeData;
import com.vshop.service.CountryService;
import com.vshop.service.SequenceService;
import com.vshop.utils.Md5Encrypt;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 国家列表
 *
 * @author lm
 * @date 2019/03/07
 */
@RestController
@Api(description = "国家列表")
@Slf4j
public class CountryListController {
    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private CountryService countryService;

    @CrossOrigin
    @PostMapping(value = "countryList", produces = "application/json;charset=utf-8")
    @ResponseBody
    @ApiOperation(value = "国家列表", response = ResponseCountryList.class)
    public String countryList(@ApiParam @RequestBody RequestCountryList request) {
        // 1，生成流水号
        String connSeqNo = sequenceService.getPackageTaskNo();
        // 2,生成当前时间戳
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String curtime = df.format(new Date());
        //3,定义要回复的内容
        String jsonString;
        ExceptionRequest utils = new ExceptionRequest();

        String requestStr = JSON.toJSONString(request);
        if (requestStr == null) {
            log.info("请求报文不合法:requestStr为空");
            jsonString = utils.dataWeiKong(connSeqNo, curtime);
            return jsonString;
        } else {
            log.info("前端请求报文是：" + requestStr);
            RequestCountryList requestPackage = JSONArray.parseObject(requestStr, RequestCountryList.class);
            String requestSign = requestPackage.getSign();
            if (requestPackage.getSign() == null) {
                log.info("请求报文不合法:sign为空");
                jsonString = utils.dataWeiKong(connSeqNo, curtime);
                return jsonString;
            } else {
                log.info("请求的签名是：" + requestSign);
                RequestCountryListData requestData = requestPackage.getData();
                if (requestPackage.getData() == null) {
                    log.info("请求报文不合法:data为空");
                    jsonString = utils.dataWeiKong(connSeqNo, curtime);
                    return jsonString;
                } else {
                    String ConnSeqNo = requestData.getConnSeqNo();
                    String partnerCode = requestData.getPartnerCode();
                    String tradeTime = requestData.getTradeTime();
                    String tradeType = requestData.getTradeType();
                    String lang = requestData.getLang();
                    String version = requestData.getVersion();
                    RequestCountryListTradeData requestDataTradeData = requestData.getTradeData();

                    //lang为空或者为null时，默认为cn
                    if (requestDataTradeData == null || StringUtils.isBlank(ConnSeqNo) || StringUtils.isBlank(partnerCode) || StringUtils.isBlank(tradeTime) || StringUtils.isBlank(tradeType) || lang == null || version == null) {
                        log.info("请求报文不合法:data参数不合法");
                        jsonString = utils.dataWeiKong(connSeqNo, curtime);
                        return jsonString;
                    } else {
                        // 将请求体json转成String   // 将Str拿去计算签名
                        String str = JSON.toJSONString(requestData);
                        String sign = utils.calculateSignature(str);
                        log.info("计算的签名是：" + sign);

                        //中文
                        if (lang.equals("cn") || StringUtils.isBlank(lang)) {
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                log.info("签名验证失败！");
                                jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "签名有误，请确认签名！");
                                return jsonString;
                            } else {//签名验证通过
                                //用partnerCode和country去数据库查询这个国家列表
                                List<ResponseCountryListTradeData> tradeDataList = new ArrayList<ResponseCountryListTradeData>();
                                ResponseCountryListTradeData tradeData = null;
                                List<Country> CountryList = new ArrayList<Country>();
                                String continentName = requestDataTradeData.getContinentName();

                                if (StringUtils.isNotBlank(continentName)) {
                                    //有大洲信息
                                    CountryList = countryService.queryCountryByContinent(continentName);

                                    if (CountryList != null && CountryList.size() > 0) {
                                        for (Country c : CountryList) {
                                            tradeData = new ResponseCountryListTradeData();
                                            tradeData.setCountryName(c.getCountry_name());
                                            tradeDataList.add(tradeData);
                                        }

                                    } else {
                                        log.info("查询有误");
                                        jsonString = utils.unknownError(ConnSeqNo, curtime, tradeType);
                                        return jsonString;
                                    }


                                } else {//没有大洲信息
                                    CountryList = countryService.queryAllCountry();
                                    if (CountryList != null && !CountryList.isEmpty()) {
                                        for (Country c : CountryList) {
                                            String country_name = c.getCountry_name();
                                            tradeData = new ResponseCountryListTradeData();
                                            tradeData.setCountryName(country_name);
                                            tradeDataList.add(tradeData);
                                        }

                                    } else {
                                        log.info("查询有误");
                                        jsonString = utils.unknownError(ConnSeqNo, curtime, tradeType);
                                        return jsonString;
                                    }

                                }


                                ResponseCountryListData data = new ResponseCountryListData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeRstCode("0000");
                                data.setTradeRstMessage("成功");
                                data.setTradeData(tradeDataList);

                                ResponseCountryList responseCountryList = new ResponseCountryList();
                                responseCountryList.setData(data);
                                responseCountryList.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                                jsonString = JSON.toJSONString(responseCountryList);
                                log.info("响应报文：" + jsonString);
                                return jsonString;


                            }


                        } else {//英文
                            if (!requestSign.equalsIgnoreCase(sign)) {
                                log.info("签名验证失败！");
                                jsonString = utils.signatureFailure(ConnSeqNo, tradeTime, tradeType, "0001", "The signature is wrong, please confirm the signature!");
                                return jsonString;
                            } else {//签名验证通过
                                //用partnerCode和country去数据库查询这个国家列表
                                List<ResponseCountryListTradeData> tradeDataList = new ArrayList<ResponseCountryListTradeData>();
                                ResponseCountryListTradeData tradeData = null;

                                List<Country> CountryList = new ArrayList<Country>();
                                String continentName = requestDataTradeData.getContinentName();

                                if (StringUtils.isNotBlank(continentName)) {
                                    //有大洲信息
                                    CountryList = countryService.queryCountryByContinentEN(continentName);
                                    if (CountryList != null && !CountryList.isEmpty()) {
                                        for (Country c : CountryList) {
                                            tradeData = new ResponseCountryListTradeData();
                                            tradeData.setCountryName(c.getCountry_name_en());
                                            tradeDataList.add(tradeData);
                                        }

                                    } else {
                                        log.info("查询有误");
                                        jsonString = utils.unknownError(ConnSeqNo, curtime, tradeType);
                                        return jsonString;
                                    }


                                } else {//没有大洲信息
                                    CountryList = countryService.queryAllCountry();
                                    if (CountryList != null && !CountryList.isEmpty()) {
                                        for (Country c : CountryList) {
                                            String country_name_en = c.getCountry_name_en();
                                            tradeData = new ResponseCountryListTradeData();
                                            tradeData.setCountryName(country_name_en);
                                            tradeDataList.add(tradeData);
                                        }

                                    } else {
                                        log.info("查询有误");
                                        jsonString = utils.unknownError(ConnSeqNo, curtime, tradeType);
                                        return jsonString;
                                    }

                                }

                                ResponseCountryListData data = new ResponseCountryListData();
                                data.setConnSeqNo(ConnSeqNo);
                                data.setPartnerCode(partnerCode);
                                data.setTradeType(tradeType);
                                data.setTradeTime(tradeTime);
                                data.setTradeRstCode("0000");
                                data.setTradeRstMessage("success");
                                data.setTradeData(tradeDataList);

                                ResponseCountryList responseCountryList = new ResponseCountryList();
                                responseCountryList.setData(data);
                                responseCountryList.setSign(Md5Encrypt.md5(JSON.toJSONString(data)));

                                jsonString = JSON.toJSONString(responseCountryList);
                                log.info("响应报文：" + jsonString);
                                return jsonString;

                            }


                        }

                    }
                }
            }
        }
    }

}

